package com.aj.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import Decoder.BASE64Decoder;
import Decoder.BASE64Encoder;
import android.util.Log;

/*密钥长度8位*/
public class DesBase64Tool {
	private static final String TAG = DesBase64Tool.class.getName();
	/*
	 * private static ResourceBundle rb = ResourceBundle
	 * .getBundle("config.system");
	 */
	public static final String DEF_KEY = "AJ100000";

	/* 解密 */
	public static String decryptDES(String decryptString) {
		return decryptDES(decryptString, DEF_KEY);
	}

	/* 加密 */
	public static String encryptDES(String encryptString) {
		return encryptDES(encryptString, DEF_KEY);
	}

	/* 加密 */
	public static String encryptDES(String encryptString, String encryptKey) {
		SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");
		try {
			Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, key);
			byte[] encryptedData = cipher.doFinal(encryptString
					.getBytes("UTF-8"));
			String str = new BASE64Encoder().encode(encryptedData);
			return toHexFromString(str);
		} catch (Exception e) {
			Log.e(TAG, "DES加密出错key:" + encryptKey + "===str:" + encryptString,
					e);
			e.printStackTrace();
		}
		return null;

	}

	/* 解密 */
	public static String decryptDES(String decryptString, String decryptKey) {
		try {
			if (decryptKey == null) {
				decryptKey = DEF_KEY;
			}
			String str = toStringFromHex(decryptString);
			byte[] byteMi = new BASE64Decoder().decodeBuffer(str);
			SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes(), "DES");
			Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
			cipher.init(Cipher.DECRYPT_MODE, key);
			byte decryptedData[] = cipher.doFinal(byteMi);
			return new String(decryptedData, "UTF-8");
		} catch (Exception e) {
			Log.e(TAG, "DES解密出错key:" + decryptKey + "===str:" + decryptString,
					e);
			e.printStackTrace();
		}
		return null;
	}

	// s-->16
	private static String toHexFromString(String s) {
		StringBuffer str = new StringBuffer();
		for (int i = 0; i < s.length(); i++) {
			int ch = s.charAt(i);
			if (ch != 10 && ch != 13)
				str.append(Integer.toHexString(ch));
		}
		return str.toString();
	}

	// 16-->s
	private static String toStringFromHex(String s) {
		byte[] baKeyword = new byte[s.length() / 2];
		for (int i = 0; i < baKeyword.length; i++) {
			try {
				baKeyword[i] = (byte) (0xff & Integer.parseInt(
						s.substring(i * 2, i * 2 + 2), 16));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		try {
			s = new String(baKeyword, "utf-8");// UTF-16le:Not
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return s;
	}

}